package com.portal.executor.utils;

import java.util.concurrent.*;

/**
 * 线程池创建工具类
 *
 * @author Amadeus
 * @date 2022/07/07
 */
public class ThreadPoolManager {

    private ThreadPoolManager() {

    }

    /**
     * 有界队列
     *
     * @param corePoolSize
     * @param maximumPoolSize
     * @param queueSize
     * @param keepAliveTime
     * @return
     */
    public static ThreadPoolExecutor createThreadPoolExecutorFree(int corePoolSize, int maximumPoolSize, int queueSize, long keepAliveTime) {
        return new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(queueSize), Executors.defaultThreadFactory());
    }

    /**
     * 无界队列
     *
     * @param corePoolSize
     * @param maximumPoolSize
     * @param keepAliveTime
     * @return
     */
    public static ThreadPoolExecutor createThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime) {
        return new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(), Executors.defaultThreadFactory());
    }

    /**
     * 按时执行队列
     *
     * @param threadCount
     * @return
     */
    public static ScheduledThreadPoolExecutor createScheduledThreadPoolExecutor(
            int threadCount) {
        return new ScheduledThreadPoolExecutor(
                threadCount, Executors.defaultThreadFactory());
    }


    public static ScheduledFuture<?> scheduleGeneral(Runnable r, long delay, ScheduledThreadPoolExecutor scheduledThreadPool) {
        try {
            return scheduledThreadPool.schedule(r, delay, TimeUnit.MILLISECONDS);
        } catch (RejectedExecutionException e) {
            return null;
        }
    }

    public static ScheduledFuture<?> scheduleGeneralAtFixedRate(Runnable r, long initial, long delay, ScheduledThreadPoolExecutor scheduledThreadPool) {
        try {
            return scheduledThreadPool.scheduleAtFixedRate(r, initial, delay, TimeUnit.SECONDS);
        } catch (RejectedExecutionException e) {
            return null;
        }
    }


}
